import axios from "axios";
import http from "http";
import https from "https";

const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });

import { getToken, clearToken } from "./chadan-login.js";

const request = axios.create({
  httpAgent,
  httpsAgent,
  timeout: 10 * 1000,
});

request.interceptors.request.use(function (config) {
  config.headers['user-agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36';
  // console.info(`[REQUEST] ${config.method.toUpperCase()} ${config.url}`);
  return config;
});

request.interceptors.response.use(async function (response) {
  const config = response.config;

  // console.info(`[RESPONSE] ${config.method.toUpperCase()} ${config.url} ${response.status}-${response.statusText}`);

  const data = response.data;
  try {
    if(data.errorCode === 2000) {
      console.log('茶蛋 JSESSIONID 失效')
      clearToken();

      const token = await getToken();
      // config.data = config.data.replace(/(JSESSIONID=)[^&]*/, `JSESSIONID=${token}`);
      const dataObject = Object.fromEntries(new URLSearchParams(config.data));
      dataObject['JSESSIONID'] = token;
      config.data = dataObject;
      delete config.headers["Content-Length"];

      return request(config);
    }
  }catch (e) {
    console.error(e)
  }
  return response;
},function (error) {
  const config = error.config;
  console.error(`[RESPONSE ERROR] ${error.message} ${config?.url}`);
  return Promise.reject(new Error(error.message));
});

export default request;
